package top.dbpanda.cmsjpa.learn.juc;

import java.util.ArrayList;
import java.util.concurrent.*;

public class CompletableFutureDemo {
    public static void main(String[] args) {
        CopyOnWriteArrayList<Integer> integers = new CopyOnWriteArrayList<>();
        ArrayList<Character> res = new ArrayList<>();

        integers.add(1);
        integers.add(2);
        integers.add(3);
        integers.add(4);

        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(1, 2, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>() //无界队列
                , new ThreadPoolExecutor.AbortPolicy());
        CompletableFuture[] completableFutures = integers.stream().map(integer -> CompletableFuture.supplyAsync(() -> calcASCII(integer), poolExecutor).thenApply(i -> {
            char c = (char) i.intValue();
            System.out.println("【阶段2】线程" + Thread.currentThread().getName() + "执行完毕，" + "已将int" + i + "转为了字符" + c);
            return c;
        }).whenComplete((ch, e) -> {
            res.add(ch);
            System.out.println("【阶段3】线程" + Thread.currentThread().getName() + "执行完毕，" + "已将char" + ch + "放到结果集");
            poolExecutor.shutdown();
        })).toArray(CompletableFuture[]::new);
        CompletableFuture.allOf(completableFutures).join();
        System.out.println("完成" + res);

    }

    private static Integer calcASCII(Integer integer) {
        try {
            if (integer == 1) {
                Thread.sleep(5000);
            } else {
                Thread.sleep(1000);
            }
            integer = integer + 64;
            System.out.println("[阶段1]线程" + Thread.currentThread().getName() + "执行完毕，已将" + integer + "转换A(BCD)对应ASCII值");

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return integer;
    }
}
